package com.visionet.school.app.web.repository.file.impl;

import com.visionet.school.app.web.common.utils.PageUtils;
import com.visionet.school.app.web.entity.file.vo.FileVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dzd on 2017/3/29.
 */
public class FileClassRepositoryImpl {

    @Resource
    private JdbcTemplate jdbcTemplate;

    public Page<FileVo> queryClassPhoto(FileVo fileVo){
        StringBuffer sql = new StringBuffer();
        List<Object> params = new ArrayList<>();
        sql.append("SELECT tf.id,tf.file_name,tf.file_path,tf.create_date FROM t_file AS tf WHERE tf.is_deleted = '0' and tf.id IN ");
        sql.append("(SELECT tmf.file_id FROM t_member_file AS tmf WHERE 1=1 ");
        if(StringUtils.isNotBlank(fileVo.getMemberFileType())){
            sql.append("and tmf.member_file_type = ? ");
            params.add(fileVo.getMemberFileType());
        }
        sql.append("and tmf.member_id IN ( ");
        for(String s : fileVo.getMemberIds()){
            sql.append("'").append(s).append("',");
        }
        StringBuffer sqlStr = new StringBuffer(sql.substring(0,sql.length()-1));
        sqlStr.append(")) ORDER BY tf.create_date");
        PageRequest page = PageUtils.getPageRequestInfo(fileVo.getPageInfo());
        if(page == null){
            page = new PageRequest(0, 10);
        }
        int currentPage = page.getPageNumber();
        int pageSize = page.getPageSize();
        int size = jdbcTemplate.queryForInt("select count(*) from ("+sqlStr.toString()+") as c", params.toArray());
        List<FileVo> list = jdbcTemplate.query("select t.* from ("+sqlStr+") as t limit  "+ currentPage * pageSize+","+pageSize, params.toArray(), new RowMapper<FileVo>(){
            public FileVo mapRow(ResultSet rs, int rowNum) throws SQLException {
                FileVo fileVo = new FileVo();
                fileVo.setFilePath(rs.getString("file_path"));
                fileVo.setCreateDate(rs.getString("create_date"));
                return fileVo;
            }
        });
        Page<FileVo> pageFile = new PageImpl<>(list, page, size);
        if(pageFile.getSize()>0) {
            return pageFile;
        }
        return null;
    }
}
